import React, { useState, useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { Calendar, Clock, ArrowLeft, ChevronLeft, ChevronRight, Book, ChevronDown, ChevronUp } from 'lucide-react';
import { marked } from 'marked';
import hljs from 'highlight.js';
import { loadNoteById, loadNotesByCategory, getNoteCategories, loadNoteByIdFromAnyCategory } from '../utils/noteLoader';
import { processCodeBlocks, initCopyHandlers } from '../utils/codeBlockProcessor';
import TableOfContents from '../components/TableOfContents';
import SEOHead from '../components/SEOHead';

const NotePost = () => {
  const { category, id } = useParams();
  const navigate = useNavigate();
  const [note, setNote] = useState(null);
  const [categoryNotes, setCategoryNotes] = useState([]);
  const [categories, setCategories] = useState([]);
  const [prevNote, setPrevNote] = useState(null);
  const [nextNote, setNextNote] = useState(null);
  const [loading, setLoading] = useState(true);
  const [showCategoryNotes, setShowCategoryNotes] = useState(true);

  useEffect(() => {
    // 重置所有状态
    setNote(null);
    setCategoryNotes([]);
    setCategories([]);
    setPrevNote(null);
    setNextNote(null);
    setLoading(true);

    // 配置 marked
    marked.setOptions({
      highlight: function(code, lang) {
        const language = hljs.getLanguage(lang) ? lang : 'plaintext';
        return hljs.highlight(code, { language }).value;
      },
      breaks: true,
      gfm: true,
      langPrefix: 'hljs language-'
    });

    // 加载笔记和导航信息
    const loadNote = async () => {
      try {
        // 首先尝试按传统方式加载
        let foundNote = await loadNoteById(category, id);
        
        // 如果没找到，尝试按ID从所有笔记中查找
        if (!foundNote) {
          foundNote = await loadNoteByIdFromAnyCategory(id);
        }
        
        const [notesInCategory, allCategories] = await Promise.all([
          loadNotesByCategory(category),
          getNoteCategories()
        ]);
        
        if (foundNote) {
          setNote(foundNote);
          setCategoryNotes(notesInCategory);
          setCategories(allCategories);
          
          // 找到当前笔记在分类中的位置
          const currentIndex = notesInCategory.findIndex(n => n.id === id);
          if (currentIndex !== -1) {
            setPrevNote(currentIndex > 0 ? notesInCategory[currentIndex - 1] : null);
            setNextNote(currentIndex < notesInCategory.length - 1 ? notesInCategory[currentIndex + 1] : null);
          }
        }
      } catch (error) {
        console.error('加载笔记失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadNote();
  }, [category, id]);

  // 初始化复制功能
  useEffect(() => {
    if (note) {
      const timer = setTimeout(() => {
        initCopyHandlers();
      }, 100);
      
      return () => clearTimeout(timer);
    }
  }, [note]);

  const handleNavigateToNote = (targetNote) => {
    if (!targetNote) return;
    navigate(`/notes/${category}/${targetNote.id}`);
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const getCategoryInfo = (categoryKey) => {
    // 首先查找主分类
    const mainCategory = categories.find(cat => cat.key === categoryKey);
    if (mainCategory) {
      return mainCategory;
    }
    
    // 然后查找子分类
    for (const category of categories) {
      if (category.subcategories) {
        const subcategory = category.subcategories.find(sub => sub.key === categoryKey);
        if (subcategory) {
          return {
            ...subcategory,
            parentName: category.name,
            parentKey: category.key
          };
        }
      }
    }
    
    return { name: categoryKey, description: '' };
  };

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-3/4 mb-4"></div>
          <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2 mb-8"></div>
          <div className="space-y-3">
            <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded"></div>
            <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-5/6"></div>
            <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-4/6"></div>
          </div>
        </div>
      </div>
    );
  }

  if (!note) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12 text-center">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
          笔记未找到
        </h1>
        <Link
          to="/notes"
          className="inline-flex items-center text-spring-600 dark:text-spring-400 hover:text-spring-700 dark:hover:text-spring-300"
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回笔记列表
        </Link>
      </div>
    );
  }

  return (
    <>
      {note && (
        <SEOHead 
          title={note.title}
          description={note.excerpt}
          keywords={`${getCategoryInfo(category).name},${note.title},技术笔记,学习笔记`}
          type="article"
          publishedTime={note.date}
          author="技术博主"
        />
      )}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="flex flex-col lg:flex-row gap-8">
        {/* Sidebar */}
        <aside className="lg:w-80 lg:flex-shrink-0" role="navigation" aria-label="笔记分类导航">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 sticky top-24">
            {/* Category Header */}
            <div className="p-6 border-b border-gray-200 dark:border-gray-700">
              <div className="flex items-center mb-2">
                <Book className="h-5 w-5 mr-2" style={{ color: 'var(--color-primary)' }} />
                <h3 className="font-semibold text-gray-900 dark:text-white">
                  {getCategoryInfo(category).name}
                </h3>
              </div>
              <p className="text-sm text-gray-600 dark:text-gray-300">
                {getCategoryInfo(category).description}
              </p>
            </div>

            {/* Category Notes List */}
            <div className="p-4">
              <button
                onClick={() => setShowCategoryNotes(!showCategoryNotes)}
                className="w-full flex items-center justify-between p-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg transition-colors"
              >
                <span>本分类笔记 ({categoryNotes.length})</span>
                {showCategoryNotes ? (
                  <ChevronUp className="h-4 w-4" />
                ) : (
                  <ChevronDown className="h-4 w-4" />
                )}
              </button>

              {showCategoryNotes && (
                <nav className="mt-2 space-y-1 max-h-96 overflow-y-auto">
                  {categoryNotes.map(categoryNote => (
                    <Link
                      key={categoryNote.id}
                      to={`/notes/${category}/${categoryNote.id}`}
                      className={`block px-3 py-2 rounded-lg text-sm transition-colors ${
                        categoryNote.id === id
                          ? 'font-medium'
                          : 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-white'
                      }`}
                      style={categoryNote.id === id ? {
                        backgroundColor: 'var(--color-primary-light)',
                        color: 'var(--color-primary-dark)'
                      } : {}}
                    >
                      <div className="truncate" title={categoryNote.title}>
                        {categoryNote.title}
                      </div>
                    </Link>
                  ))}
                </nav>
              )}
            </div>
          </div>
        </aside>

        {/* Main Content */}
        <div className="flex-1 lg:max-w-4xl" role="main">
          {/* Breadcrumb */}
          <nav className="flex items-center space-x-2 text-sm text-gray-500 dark:text-gray-400 mb-6" aria-label="面包屑导航">
            <Link to="/notes" className="hover:theme-color transition-colors">
              笔记
            </Link>
            <ChevronRight className="h-4 w-4" />
            <Link 
              to={`/notes/${category}`} 
              className="hover:theme-color transition-colors"
            >
              {getCategoryInfo(category).name}
            </Link>
            <ChevronRight className="h-4 w-4" />
            <span className="text-gray-900 dark:text-white font-medium truncate">
              {note.title}
            </span>
          </nav>

          {/* Back Button */}
          <Link
            to={`/notes/${category}`}
            className="inline-flex items-center mb-8 transition-colors theme-color hover:opacity-80"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            返回 {getCategoryInfo(category).name}
          </Link>

          {/* Note Header */}
          <header className="mb-8" itemScope itemType="https://schema.org/TechArticle">
            <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-6" itemProp="headline">
              {note.title}
            </h1>
            
            <meta itemProp="datePublished" content={note.date} />
            <meta itemProp="author" content="技术博主" />
            <meta itemProp="description" content={note.excerpt} />
            
            <div className="flex flex-wrap items-center gap-6 text-sm text-gray-500 dark:text-gray-400 mb-6">
              <div className="flex items-center">
                <Calendar className="h-4 w-4 mr-2" />
                {formatDate(note.date)}
              </div>
              <div className="flex items-center">
                <Clock className="h-4 w-4 mr-2" />
                {note.readTime}
              </div>
            </div>

            {note.excerpt && (
              <div 
                className="border-l-4 p-4 rounded-r-lg"
                style={{
                  backgroundColor: 'var(--color-primary-light)',
                  borderLeftColor: 'var(--color-primary)'
                }}
              >
                <p className="text-gray-700 dark:text-gray-300 italic">
                  {note.excerpt}
                </p>
              </div>
            )}
          </header>

          {/* Note Content */}
          <article className="prose prose-lg max-w-none markdown-content mb-12" itemProp="articleBody">
            <div dangerouslySetInnerHTML={{ __html: processCodeBlocks(marked(note.content)) }} />
          </article>

          {/* Note Navigation */}
          <nav className="pt-8 border-t border-gray-200 dark:border-gray-700" aria-label="笔记导航">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
              {/* Previous Note */}
              {prevNote ? (
                <button
                  onClick={() => handleNavigateToNote(prevNote)}
                  className="group flex items-center p-4 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg hover:shadow-md hover:border-spring-300 dark:hover:border-spring-600 transition-all duration-200 w-full text-left"
                >
                  <div className="flex-shrink-0 mr-4">
                    <div 
                      className="w-10 h-10 rounded-full flex items-center justify-center transition-colors"
                      style={{
                        backgroundColor: 'var(--color-primary-light)',
                        '--hover-bg': 'var(--color-primary-light)'
                      }}
                      onMouseEnter={(e) => e.target.style.backgroundColor = 'var(--color-primary)'}
                      onMouseLeave={(e) => e.target.style.backgroundColor = 'var(--color-primary-light)'}
                    >
                      <ChevronLeft className="h-5 w-5" style={{ color: 'var(--color-primary)' }} />
                    </div>
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">上一篇</p>
                    <h3 className="text-base font-medium text-gray-900 dark:text-white transition-colors line-clamp-2 group-hover:theme-color">
                      {prevNote.title}
                    </h3>
                  </div>
                </button>
              ) : (
                <div className="flex items-center p-4 bg-gray-50 dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700 rounded-lg opacity-50">
                  <div className="flex-shrink-0 mr-4">
                    <div className="w-10 h-10 bg-gray-200 dark:bg-gray-700 rounded-full flex items-center justify-center">
                      <ChevronLeft className="h-5 w-5 text-gray-400" />
                    </div>
                  </div>
                  <div className="flex-1">
                    <p className="text-sm text-gray-400 dark:text-gray-500">没有更多笔记了</p>
                  </div>
                </div>
              )}

              {/* Next Note */}
              {nextNote ? (
                <button
                  onClick={() => handleNavigateToNote(nextNote)}
                  className="group flex items-center p-4 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg hover:shadow-md hover:border-spring-300 dark:hover:border-spring-600 transition-all duration-200 w-full text-left"
                >
                  <div className="flex-1 min-w-0 text-right">
                    <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">下一篇</p>
                    <h3 className="text-base font-medium text-gray-900 dark:text-white transition-colors line-clamp-2 group-hover:theme-color">
                      {nextNote.title}
                    </h3>
                  </div>
                  <div className="flex-shrink-0 ml-4">
                    <div 
                      className="w-10 h-10 rounded-full flex items-center justify-center transition-colors"
                      style={{
                        backgroundColor: 'var(--color-primary-light)',
                        '--hover-bg': 'var(--color-primary-light)'
                      }}
                      onMouseEnter={(e) => e.target.style.backgroundColor = 'var(--color-primary)'}
                      onMouseLeave={(e) => e.target.style.backgroundColor = 'var(--color-primary-light)'}
                    >
                      <ChevronRight className="h-5 w-5" style={{ color: 'var(--color-primary)' }} />
                    </div>
                  </div>
                </button>
              ) : (
                <div className="flex items-center p-4 bg-gray-50 dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700 rounded-lg opacity-50">
                  <div className="flex-1 text-right">
                    <p className="text-sm text-gray-400 dark:text-gray-500">没有更多笔记了</p>
                  </div>
                  <div className="flex-shrink-0 ml-4">
                    <div className="w-10 h-10 bg-gray-200 dark:bg-gray-700 rounded-full flex items-center justify-center">
                      <ChevronRight className="h-5 w-5 text-gray-400" />
                    </div>
                  </div>
                </div>
              )}
            </div>
          </nav>

          {/* Note Footer */}
          <footer className="pt-6 border-t border-gray-200 dark:border-gray-700">
            <div className="flex justify-between items-center">
              <div className="text-sm text-gray-500 dark:text-gray-400">
                最后更新：{formatDate(note.date)}
              </div>
              <Link
                to={`/notes/${category}`}
                className="inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
              >
                查看更多笔记
              </Link>
            </div>
          </footer>
        </div>

        {/* Table of Contents */}
        <aside className="lg:w-80 lg:flex-shrink-0" role="complementary" aria-label="文章目录">
          <div className="lg:hidden mb-8">
            <TableOfContents content={note.content} />
          </div>
          <div className="hidden lg:block">
            <TableOfContents content={note.content} />
          </div>
        </aside>
      </div>
      </div>
    </>
  );
};

export default NotePost;
